package top.zymall.sms.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.zy.common.zymallcommon.utils.exception.ZymalException;
import top.zymall.sms.properties.SmsProperties;
import top.zymall.sms.sms.SmsUtil;

import java.util.Collections;
import java.util.Map;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 10:28 2019/7/11
 */
@EnableConfigurationProperties(value = SmsProperties.class)
@Component
@Slf4j
public class ListenerSmsMessage {
     @Autowired
     private SmsUtil smsUtil;

     @Autowired
     private SmsProperties smsProperties;

    @RabbitListener(bindings = @QueueBinding(value =
    @Queue(value = "zymall.sms.verify.queue",autoDelete = "false")
            ,exchange = @Exchange(value = "zymall.sms.exchange",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC)
            ,key ="send.sms" ))
    public void listenerMqSendSms(String message){
        String mobile=null;
        String code=null;
        Map<String, String> paramMap=Collections.emptyMap();
        try {
            paramMap = JSON.parseObject(message, new TypeReference<Map<String, String>>() {});
            mobile=paramMap.remove("mobile");
            code= paramMap.get("code");
        } catch (Exception e) {
            log.error("[短信服务]解析消息异常",e);
        }
        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(code)){
            return;
        }
        try {
            String response = smsUtil.sendAliSms(mobile,smsProperties.getVerifyTemplateCode(),JSONObject.toJSONString(paramMap));
            if ("OK".equals(response)){
                log.info("[短信服务]发送短信验证码成功，手机号:{},验证码:{}",mobile,code);
            }else {
                log.info("[短信服务]发送短信验证码失败，手机号:{},验证码:{}",mobile,code);
            }
        } catch (Exception e) {
            log.error("[短信服务]发送短信验证码异常",e);
        }
    }
}
